package com.draven.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.draven.mall.entity.Order;
import com.draven.mall.entity.Rider;
import com.draven.mall.entity.DispatchConfig;
import com.draven.mall.mapper.OrderMapper;
import com.draven.mall.service.OrderService;
import com.draven.mall.service.RiderService;
import com.draven.mall.service.DispatchConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Calendar;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private RiderService riderService;

    @Autowired
    private DispatchConfigService dispatchConfigService;

    @Override
    public Map<String, Object> getAvailableOrders(Integer page, Integer size) {
        // 默认分页参数
        page = (page == null || page < 1) ? 1 : page;
        size = (size == null || size < 1) ? 10 : size;
        
        // 创建分页对象
        Page<Order> pageParam = new Page<>(page, size);
        
        // 查询待接单订单
        IPage<Order> pageResult = baseMapper.selectAvailableOrders(pageParam);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return result;
    }

    @Override
    @Transactional
    public boolean takeOrder(Long orderId, Long riderId) {
        // 查询订单是否存在且状态为待接单(状态1)
        Order order = getById(orderId);
        if (order == null || order.getStatus() != 1) {
            return false;
        }
        
        // 更新订单状态为已接单配送中(状态2)并分配骑手
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, orderId)
                    .eq(Order::getStatus, 1) // 确保状态为待接单，防止并发问题
                    .set(Order::getStatus, 2)
                    .set(Order::getRiderId, riderId)
                    .set(Order::getUpdatedTime, new Date());
        
        return update(updateWrapper);
    }

    @Override
    @Transactional
    public boolean completeOrder(Long orderId, Long riderId) {
        // 查询订单是否存在且状态为配送中(状态2)且是该骑手的订单
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getId, orderId)
                   .eq(Order::getStatus, 2)
                   .eq(Order::getRiderId, riderId);
        
        if (count(queryWrapper) == 0) {
            return false;
        }
        
        // 更新订单状态为已完成(状态3)
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, orderId)
                    .eq(Order::getStatus, 2)
                    .eq(Order::getRiderId, riderId)
                    .set(Order::getStatus, 3)
                    .set(Order::getUpdatedTime, new Date());
        
        return update(updateWrapper);
    }

    @Override
    public Map<String, Object> getInProgressOrders(Long riderId, Integer page, Integer size) {
        // 默认分页参数
        page = (page == null || page < 1) ? 1 : page;
        size = (size == null || size < 1) ? 10 : size;
        
        // 创建分页对象
        Page<Order> pageParam = new Page<>(page, size);
        
        // 查询配送中订单
        IPage<Order> pageResult = baseMapper.selectInProgressOrders(pageParam, riderId);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return result;
    }

    @Override
    public Map<String, Object> getCompletedOrders(Long riderId, Integer page, Integer size) {
        // 默认分页参数
        page = (page == null || page < 1) ? 1 : page;
        size = (size == null || size < 1) ? 10 : size;
        
        // 创建分页对象
        Page<Order> pageParam = new Page<>(page, size);
        
        // 查询已完成订单
        IPage<Order> pageResult = baseMapper.selectCompletedOrders(pageParam, riderId);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return result;
    }

    @Override
    @Transactional
    public Long createOrder(Order order) {
        // 设置订单编号（可以根据实际需求设置编号生成规则）
        String orderNumber = "OD" + System.currentTimeMillis();
        order.setOrderNo(orderNumber);
        
        // 如果没有指定配送模式，默认为系统派单
        if (order.getDeliveryMode() == null) {
            order.setDeliveryMode(1); // 系统派单
        }
        
        // 设置订单状态为已支付待接单
        order.setStatus(1);
        
        // 保存订单
        save(order);
        
        // 如果是系统派单模式，立即尝试分配骑手
        if (order.getDeliveryMode() == 1) {
            assignOrderToRider(order.getId());
        }
        
        return order.getId();
    }

    @Override
    @Transactional
    public boolean assignOrderToRider(Long orderId) {
        // 查询订单
        Order order = getById(orderId);
        if (order == null || order.getStatus() != 1) {
            return false;
        }
        
        // 获取可用骑手列表（开启抢单状态的）
        List<Rider> availableRiders = riderService.getAvailableRiders();
        if (availableRiders.isEmpty()) {
            // 没有可用骑手，订单保持待接单状态
            return false;
        }
        
        // 获取当前激活的调度算法配置
        DispatchConfig dispatchConfig = dispatchConfigService.getActiveConfig();
        
        // 默认为随机分配
        int algorithmType = 1;
        if (dispatchConfig != null) {
            algorithmType = dispatchConfig.getAlgorithmType();
        }
        
        // 选择骑手
        Rider rider = null;
        
        switch (algorithmType) {
            case 1: // 随机分配
                rider = randomAssign(availableRiders);
                break;
            case 2: // 最近骑手优先
                rider = nearestRiderAssign(availableRiders, order);
                break;
            case 3: // 评分最高骑手优先
                rider = highestRatingAssign(availableRiders);
                break;
            case 4: // 最少订单骑手优先
                rider = leastOrdersAssign(availableRiders);
                break;
            case 5: // 综合算法
                rider = comprehensiveAssign(availableRiders, order, dispatchConfig);
                break;
            default:
                rider = randomAssign(availableRiders);
        }
        
        if (rider == null) {
            // 如果没有找到适合的骑手，退回到随机分配
            rider = randomAssign(availableRiders);
        }
        
        // 更新订单信息
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getId, orderId)
                    .eq(Order::getStatus, 1) // 确保状态为待接单
                    .set(Order::getRiderId, rider.getId())
                    .set(Order::getStatus, 2) // 更新为配送中
                    .set(Order::getUpdatedTime, new Date());
        
        return update(updateWrapper);
    }
    
    /**
     * 随机分配算法
     */
    private Rider randomAssign(List<Rider> riders) {
        if (riders.isEmpty()) {
            return null;
        }
        int randomIndex = new java.util.Random().nextInt(riders.size());
        return riders.get(randomIndex);
    }
    
    /**
     * 最近骑手优先算法（改进实现）
     */
    private Rider nearestRiderAssign(List<Rider> riders, Order order) {
        if (riders.isEmpty()) {
            return null;
        }
        
        // 获取订单商家信息和用户地址
        Long merchantId = order.getMerchantId();
        String userAddress = order.getAddress();
        
        // 模拟每个骑手到商家的距离和到用户的距离
        Map<Long, Double> riderDistances = new HashMap<>();
        
        for (Rider rider : riders) {
            // 在实际应用中，这里应该调用地图API计算实际距离
            // 现在使用骑手ID和商家ID、用户地址的数值关系来模拟距离
            double merchantDistance = simulateDistance(rider.getId(), merchantId);
            double userDistance = simulateDistance(rider.getId(), userAddress.hashCode());
            
            // 总距离为骑手到商家的距离 + 商家到用户的距离
            double totalDistance = merchantDistance + userDistance;
            riderDistances.put(rider.getId(), totalDistance);
        }
        
        // 找出距离最短的骑手
        return riders.stream()
                    .min((r1, r2) -> {
                        Double distance1 = riderDistances.getOrDefault(r1.getId(), Double.MAX_VALUE);
                        Double distance2 = riderDistances.getOrDefault(r2.getId(), Double.MAX_VALUE);
                        return Double.compare(distance1, distance2);
                    })
                    .orElse(riders.get(0));
    }
    
    /**
     * 模拟距离计算
     * 在真实环境中，这应该被替换为地图API的距离计算
     */
    private double simulateDistance(Long id1, long id2) {
        // 使用两个ID的最后3位进行运算，模拟距离
        long value1 = id1 % 1000;
        long value2 = id2 % 1000;
        
        // 计算差值的绝对值，并归一化到0.5-10公里范围
        double diff = Math.abs(value1 - value2);
        return 0.5 + (diff % 950) / 100.0;
    }
    
    /**
     * 评分最高骑手优先算法
     */
    private Rider highestRatingAssign(List<Rider> riders) {
        if (riders.isEmpty()) {
            return null;
        }
        
        // 按评分排序（假设有评分字段），取评分最高的骑手
        return riders.stream()
                    .sorted((r1, r2) -> {
                        Float rating1 = r1.getRating();
                        Float rating2 = r2.getRating();
                        if (rating1 == null) rating1 = 0f;
                        if (rating2 == null) rating2 = 0f;
                        return Float.compare(rating2, rating1); // 降序
                    })
                    .findFirst()
                    .orElse(riders.get(0));
    }
    
    /**
     * 最少订单骑手优先算法
     */
    private Rider leastOrdersAssign(List<Rider> riders) {
        if (riders.isEmpty()) {
            return null;
        }
        
        // 计算每个骑手当前的订单数量
        Map<Long, Integer> riderOrderCounts = new HashMap<>();
        
        for (Rider rider : riders) {
            // 查询骑手当前处理中的订单数量
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getRiderId, rider.getId())
                       .eq(Order::getStatus, 2); // 配送中状态
            long countResult = count(queryWrapper);
            int orderCount = (int) countResult;
            riderOrderCounts.put(rider.getId(), orderCount);
        }
        
        // 找出订单数量最少的骑手
        return riders.stream()
                    .min((r1, r2) -> {
                        Integer count1 = riderOrderCounts.getOrDefault(r1.getId(), 0);
                        Integer count2 = riderOrderCounts.getOrDefault(r2.getId(), 0);
                        return Integer.compare(count1, count2);
                    })
                    .orElse(riders.get(0));
    }
    
    /**
     * 综合算法（增强版）
     */
    private Rider comprehensiveAssign(List<Rider> riders, Order order, DispatchConfig config) {
        if (riders.isEmpty()) {
            return null;
        }
        
        // 解析权重配置
        Map<String, Double> weights = parseWeightConfig(config);
        
        // 计算每个骑手的综合得分
        Map<Rider, Double> riderScores = new HashMap<>();
        Map<String, Map<Long, Double>> factorScores = calculateFactorScores(riders, order);
        
        for (Rider rider : riders) {
            // 计算综合得分
            double totalScore = 0.0;
            
            // 距离因素 (距离越近，分数越高)
            double distanceScore = factorScores.get("distance").getOrDefault(rider.getId(), 0.0);
            totalScore += distanceScore * weights.getOrDefault("distance", 0.5);
            
            // 评分因素 (评分越高，分数越高)
            double ratingScore = factorScores.get("rating").getOrDefault(rider.getId(), 0.0);
            totalScore += ratingScore * weights.getOrDefault("rating", 0.3);
            
            // 订单量因素 (订单越少，分数越高)
            double orderScore = factorScores.get("orders").getOrDefault(rider.getId(), 0.0);
            totalScore += orderScore * weights.getOrDefault("orders", 0.2);
            
            // 注意：以下是扩展特性，当前Rider实体类可能没有这些字段，实现时需要修改Rider实体类
            // 暂时注释掉，避免编译错误
            /*
            // 额外因素: 接单成功率 (如果有此数据)
            if (rider.getSuccessRate() != null) {
                double successRate = rider.getSuccessRate() / 100.0; // 转换为0-1范围
                totalScore += successRate * 0.1; // 分配10%权重给成功率
            }
            
            // 额外因素：骑手在线时长 (如果有此数据)
            if (rider.getOnlineTime() != null) {
                // 假设骑手在线时长有效范围是0-8小时
                double onlineHours = Math.min(rider.getOnlineTime() / 60.0, 8.0) / 8.0; // 归一化到0-1
                totalScore += onlineHours * 0.05; // 分配5%权重给在线时长
            }
            */
            
            riderScores.put(rider, totalScore);
        }
        
        // 找出得分最高的骑手
        return riders.stream()
                    .max((r1, r2) -> Double.compare(
                        riderScores.getOrDefault(r1, 0.0),
                        riderScores.getOrDefault(r2, 0.0)
                    ))
                    .orElse(riders.get(0));
    }
    
    /**
     * 解析权重配置
     */
    private Map<String, Double> parseWeightConfig(DispatchConfig config) {
        Map<String, Double> weights = new HashMap<>();
        weights.put("distance", 0.5); // 默认权重
        weights.put("rating", 0.3);
        weights.put("orders", 0.2);
        
        if (config != null && config.getWeightConfig() != null) {
            try {
                // 尝试解析JSON格式的权重配置
                String weightConfig = config.getWeightConfig();
                if (this.isJsonObject(weightConfig)) {
                    // 使用Jackson解析JSON
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonNode = mapper.readTree(weightConfig);
                    
                    if (jsonNode.has("distance")) {
                        weights.put("distance", jsonNode.get("distance").asDouble());
                    }
                    if (jsonNode.has("rating")) {
                        weights.put("rating", jsonNode.get("rating").asDouble());
                    }
                    if (jsonNode.has("orders")) {
                        weights.put("orders", jsonNode.get("orders").asDouble());
                    }
                }
            } catch (Exception e) {
                log.error("解析权重配置失败: " + e.getMessage());
                // 解析失败，使用默认权重
            }
        }
        
        return weights;
    }
    
    /**
     * 检查字符串是否为有效的JSON对象
     */
    private boolean isJsonObject(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            new ObjectMapper().readTree(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 计算各因素得分
     */
    private Map<String, Map<Long, Double>> calculateFactorScores(List<Rider> riders, Order order) {
        Map<String, Map<Long, Double>> factorScores = new HashMap<>();
        Map<Long, Double> distanceScores = new HashMap<>();
        Map<Long, Double> ratingScores = new HashMap<>();
        Map<Long, Double> orderScores = new HashMap<>();
        
        // 计算距离得分
        Map<Long, Double> riderDistances = new HashMap<>();
        for (Rider rider : riders) {
            double merchantDistance = simulateDistance(rider.getId(), order.getMerchantId());
            double userDistance = simulateDistance(rider.getId(), order.getAddress().hashCode());
            double totalDistance = merchantDistance + userDistance;
            riderDistances.put(rider.getId(), totalDistance);
        }
        
        // 找出最大和最小距离，用于归一化
        double maxDistance = riderDistances.values().stream().max(Double::compare).orElse(1.0);
        double minDistance = riderDistances.values().stream().min(Double::compare).orElse(0.0);
        double distanceRange = maxDistance - minDistance;
        
        // 归一化距离得分 (距离越小得分越高)
        for (Long riderId : riderDistances.keySet()) {
            double distance = riderDistances.get(riderId);
            double normalizedScore = distanceRange > 0 
                ? 1.0 - ((distance - minDistance) / distanceRange) 
                : 1.0;
            distanceScores.put(riderId, normalizedScore);
        }
        
        // 计算评分得分
        double maxRating = 5.0; // 假设最高评分为5
        for (Rider rider : riders) {
            Float rating = rider.getRating();
            double ratingScore = rating != null ? rating / maxRating : 0.5;
            ratingScores.put(rider.getId(), ratingScore);
        }
        
        // 计算订单量得分
        Map<Long, Integer> riderOrderCounts = new HashMap<>();
        for (Rider rider : riders) {
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getRiderId, rider.getId())
                       .eq(Order::getStatus, 2); // 配送中状态
            long countResult = count(queryWrapper);
            riderOrderCounts.put(rider.getId(), (int) countResult);
        }
        
        // 找出最大和最小订单数，用于归一化
        int maxOrders = riderOrderCounts.values().stream().max(Integer::compare).orElse(1);
        int minOrders = riderOrderCounts.values().stream().min(Integer::compare).orElse(0);
        int orderRange = maxOrders - minOrders;
        
        // 归一化订单量得分 (订单量越小得分越高)
        for (Long riderId : riderOrderCounts.keySet()) {
            int orderCount = riderOrderCounts.get(riderId);
            double normalizedScore = orderRange > 0 
                ? 1.0 - ((double)(orderCount - minOrders) / orderRange) 
                : 1.0;
            orderScores.put(riderId, normalizedScore);
        }
        
        factorScores.put("distance", distanceScores);
        factorScores.put("rating", ratingScores);
        factorScores.put("orders", orderScores);
        
        return factorScores;
    }

    @Override
    public Order getOrderById(Long orderId) {
        return getById(orderId);
    }
    
    @Override
    public Map<String, Object> getAllOrders(Map<String, Object> params) {
        // 提取分页参数
        Integer page = (Integer) params.getOrDefault("page", 1);
        Integer size = (Integer) params.getOrDefault("size", 10);
        String keyword = (String) params.get("keyword");
        Integer status = (Integer) params.get("status");
        
        // 创建分页对象
        Page<Order> pageParam = new Page<>(page, size);
        
        // 创建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加关键词搜索
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like(Order::getOrderNo, keyword)
                       .or()
                       .like(Order::getAddress, keyword)
                       .or()
                       .like(Order::getPhone, keyword);
        }
        
        // 添加状态筛选
        if (status != null) {
            queryWrapper.eq(Order::getStatus, status);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Order::getCreatedTime);
        
        // 执行查询
        IPage<Order> pageResult = page(pageParam, queryWrapper);
        
        // 查询关联的商家和用户信息
        // 注意：这里简化处理，实际需要根据业务需求查询关联信息
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return result;
    }
    
    @Override
    public Map<String, Object> getOrderStatistics(Map<String, Object> params) {
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        Integer merchantId = (Integer) params.get("merchantId");
        
        // 创建统计数据结果Map
        Map<String, Object> statistics = new HashMap<>();
        
        // 查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加时间范围
        if (startDate != null && !startDate.isEmpty()) {
            queryWrapper.ge(Order::getCreatedTime, startDate + " 00:00:00");
        }
        if (endDate != null && !endDate.isEmpty()) {
            queryWrapper.le(Order::getCreatedTime, endDate + " 23:59:59");
        }
        
        // 添加商家ID筛选
        if (merchantId != null) {
            queryWrapper.eq(Order::getMerchantId, merchantId);
        }
        
        // 查询订单总数
        long totalCount = count(queryWrapper);
        statistics.put("totalCount", totalCount);
        
        // 不同状态订单数量
        Map<String, Long> statusCounts = getStatusCounts(queryWrapper);
        statistics.put("statusCounts", statusCounts);
        
        // 订单金额统计
        Map<String, Object> amountStats = getAmountStatistics(queryWrapper);
        statistics.put("totalAmount", amountStats.get("totalAmount"));
        statistics.put("avgAmount", amountStats.get("avgAmount"));
        
        // 时间趋势数据
        statistics.put("trends", getOrderTrends(params));
        
        return statistics;
    }
    
    /**
     * 获取不同状态的订单数量
     */
    private Map<String, Long> getStatusCounts(LambdaQueryWrapper<Order> baseWrapper) {
        Map<String, Long> statusCounts = new HashMap<>();
        
        // 构建基础SQL查询条件
        StringBuilder whereClause = new StringBuilder(" WHERE 1=1 ");
        
        // 添加商家ID筛选
        Integer merchantId = null;
        if (baseWrapper.getExpression() != null && baseWrapper.getExpression().getNormal() != null) {
            for (Object segment : baseWrapper.getExpression().getNormal()) {
                String sqlSegment = segment.toString();
                if (sqlSegment.contains("merchant_id =")) {
                    merchantId = Integer.parseInt(sqlSegment.split("=")[1].trim());
                    whereClause.append(" AND merchant_id = ").append(merchantId);
                }
                
                if (sqlSegment.contains("created_time >=")) {
                    String startDate = sqlSegment.split(">=")[1].trim();
                    // 移除可能的单引号
                    startDate = startDate.replace("'", "");
                    whereClause.append(" AND created_time >= '").append(startDate).append("'");
                }
                
                if (sqlSegment.contains("created_time <=")) {
                    String endDate = sqlSegment.split("<=")[1].trim();
                    // 移除可能的单引号
                    endDate = endDate.replace("'", "");
                    whereClause.append(" AND created_time <= '").append(endDate).append("'");
                }
            }
        }
        
        // 执行各状态的计数查询
        String pendingSql = "SELECT COUNT(*) FROM tb_order" + whereClause + " AND status = 0";
        String waitingSql = "SELECT COUNT(*) FROM tb_order" + whereClause + " AND status = 1";
        String inProgressSql = "SELECT COUNT(*) FROM tb_order" + whereClause + " AND status = 2";
        String completedSql = "SELECT COUNT(*) FROM tb_order" + whereClause + " AND status = 3";
        String canceledSql = "SELECT COUNT(*) FROM tb_order" + whereClause + " AND status = 4";
        
        try {
            // 使用自定义方法执行SQL查询
            Long pendingCount = baseMapper.executeCountSql(pendingSql);
            Long waitingCount = baseMapper.executeCountSql(waitingSql);
            Long inProgressCount = baseMapper.executeCountSql(inProgressSql);
            Long completedCount = baseMapper.executeCountSql(completedSql);
            Long canceledCount = baseMapper.executeCountSql(canceledSql);
            
            statusCounts.put("pending", pendingCount);
            statusCounts.put("waiting", waitingCount);
            statusCounts.put("inProgress", inProgressCount);
            statusCounts.put("completed", completedCount);
            statusCounts.put("canceled", canceledCount);
        } catch (Exception e) {
            // 查询失败时返回0
            statusCounts.put("pending", 0L);
            statusCounts.put("waiting", 0L);
            statusCounts.put("inProgress", 0L);
            statusCounts.put("completed", 0L);
            statusCounts.put("canceled", 0L);
        }
        
        return statusCounts;
    }
    
    /**
     * 获取订单金额统计
     */
    private Map<String, Object> getAmountStatistics(LambdaQueryWrapper<Order> queryWrapper) {
        Map<String, Object> amountStats = new HashMap<>();
        
        // 使用SQL聚合函数查询总金额和平均金额
        StringBuilder whereSql = new StringBuilder(" WHERE 1=1");
        
        // 添加查询条件
        if (queryWrapper.getExpression() != null && !queryWrapper.getExpression().getNormal().isEmpty()) {
            for (Object segment : queryWrapper.getExpression().getNormal()) {
                String sqlSegment = segment.toString();
                
                if (sqlSegment.contains("merchant_id =")) {
                    whereSql.append(" AND ").append(sqlSegment);
                }
                
                if (sqlSegment.contains("created_time >=")) {
                    whereSql.append(" AND ").append(sqlSegment);
                }
                
                if (sqlSegment.contains("created_time <=")) {
                    whereSql.append(" AND ").append(sqlSegment);
                }
            }
        }
        
        String sumSql = "SELECT IFNULL(SUM(pay_amount), 0) as total_amount, " +
                         "IFNULL(AVG(pay_amount), 0) as avg_amount " +
                         "FROM tb_order " + whereSql.toString();
        
        // 执行SQL查询
        try {
            List<Map<String, Object>> results = baseMapper.executeSql(sumSql);
            if (results != null && !results.isEmpty()) {
                Map<String, Object> result = results.get(0);
                Double totalAmount = ((Number) result.get("total_amount")).doubleValue();
                Double avgAmount = ((Number) result.get("avg_amount")).doubleValue();
                
                amountStats.put("totalAmount", totalAmount);
                amountStats.put("avgAmount", avgAmount);
            } else {
                amountStats.put("totalAmount", 0.0);
                amountStats.put("avgAmount", 0.0);
            }
        } catch (Exception e) {
            // 查询失败，使用默认值
            amountStats.put("totalAmount", 0.0);
            amountStats.put("avgAmount", 0.0);
        }
        
        return amountStats;
    }
    
    /**
     * 获取订单趋势数据
     */
    private Map<String, Object> getOrderTrends(Map<String, Object> params) {
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        Integer merchantId = (Integer) params.get("merchantId");
        
        Map<String, Object> trends = new HashMap<>();
        
        // 若未指定时间范围，默认查询最近7天
        if (startDate == null || endDate == null) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_MONTH, -6); // 7天前
            startDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
            endDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        }
        
        // 构建SQL查询
        String trendSql = "SELECT DATE_FORMAT(created_time, '%Y-%m-%d') as date, " +
                          "COUNT(*) as order_count, " +
                          "IFNULL(SUM(pay_amount), 0) as order_amount " +
                          "FROM tb_order " +
                          "WHERE created_time BETWEEN '" + startDate + " 00:00:00' AND '" + endDate + " 23:59:59'";
        
        if (merchantId != null) {
            trendSql += " AND merchant_id = " + merchantId;
        }
        
        trendSql += " GROUP BY DATE_FORMAT(created_time, '%Y-%m-%d') " +
                    "ORDER BY date";
        
        // 执行查询
        List<Map<String, Object>> results = baseMapper.executeSql(trendSql);
        
        // 确保查询结果包含指定时间范围内的每一天
        Map<String, Map<String, Object>> dateMap = new HashMap<>();
        
        // 初始化日期范围
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date start = sdf.parse(startDate);
            Date end = sdf.parse(endDate);
            
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(start);
            
            while (!calendar.getTime().after(end)) {
                String date = sdf.format(calendar.getTime());
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", date);
                dayData.put("order_count", 0);
                dayData.put("order_amount", 0.0);
                
                dateMap.put(date, dayData);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            
            // 填充查询结果
            for (Map<String, Object> result : results) {
                String date = (String) result.get("date");
                if (dateMap.containsKey(date)) {
                    dateMap.put(date, result);
                }
            }
            
            // 提取日期标签和数据数组
            List<String> labels = new ArrayList<>();
            List<Integer> orderCounts = new ArrayList<>();
            List<Double> orderAmounts = new ArrayList<>();
            
            // 按日期顺序添加数据
            calendar.setTime(start);
            while (!calendar.getTime().after(end)) {
                String date = sdf.format(calendar.getTime());
                Map<String, Object> dayData = dateMap.get(date);
                
                labels.add(date);
                orderCounts.add(((Number) dayData.get("order_count")).intValue());
                orderAmounts.add(((Number) dayData.get("order_amount")).doubleValue());
                
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            
            trends.put("labels", labels);
            trends.put("orderCounts", orderCounts);
            trends.put("orderAmounts", orderAmounts);
            
        } catch (Exception e) {
            // 出错时返回空数据
            trends.put("labels", new ArrayList<>());
            trends.put("orderCounts", new ArrayList<>());
            trends.put("orderAmounts", new ArrayList<>());
        }
        
        return trends;
    }
    
    @Override
    public Map<String, Object> getOrderStatusDistribution() {
        Map<String, Object> distribution = new HashMap<>();
        
        try {
            // 查询各状态订单数量
            String sql = "SELECT status, COUNT(*) as count FROM tb_order GROUP BY status";
            List<Map<String, Object>> results = baseMapper.executeSql(sql);
            
            // 处理查询结果
            Map<String, Long> statusCounts = new HashMap<>();
            statusCounts.put("pending", 0L);
            statusCounts.put("waiting", 0L);
            statusCounts.put("inProgress", 0L);
            statusCounts.put("completed", 0L);
            statusCounts.put("canceled", 0L);
            
            long totalCount = 0;
            
            for (Map<String, Object> result : results) {
                Integer status = ((Number) result.get("status")).intValue();
                Long count = ((Number) result.get("count")).longValue();
                totalCount += count;
                
                switch (status) {
                    case 0:
                        statusCounts.put("pending", count);
                        break;
                    case 1:
                        statusCounts.put("waiting", count);
                        break;
                    case 2:
                        statusCounts.put("inProgress", count);
                        break;
                    case 3:
                        statusCounts.put("completed", count);
                        break;
                    case 4:
                        statusCounts.put("canceled", count);
                        break;
                }
            }
            
            distribution.put("statusCounts", statusCounts);
            distribution.put("totalCount", totalCount);
            
            // 计算各状态订单占比
            Map<String, Double> statusPercentage = new HashMap<>();
            if (totalCount > 0) {
                for (Map.Entry<String, Long> entry : statusCounts.entrySet()) {
                    double percentage = (double) entry.getValue() / totalCount * 100;
                    statusPercentage.put(entry.getKey(), Math.round(percentage * 100) / 100.0); // 保留两位小数
                }
            }
            distribution.put("statusPercentage", statusPercentage);
            
        } catch (Exception e) {
            // 查询失败，初始化默认数据
            Map<String, Long> statusCounts = new HashMap<>();
            statusCounts.put("pending", 0L);
            statusCounts.put("waiting", 0L);
            statusCounts.put("inProgress", 0L);
            statusCounts.put("completed", 0L);
            statusCounts.put("canceled", 0L);
            
            distribution.put("statusCounts", statusCounts);
            distribution.put("totalCount", 0L);
            distribution.put("statusPercentage", new HashMap<String, Double>());
        }
        
        return distribution;
    }
    
    @Override
    public Map<String, Object> getOrderRealTimeFlow(String granularity) {
        Map<String, Object> flowData = new HashMap<>();
        
        try {
            String timeFormat;
            String dateField;
            int timeRange;
            
            // 根据粒度设置SQL参数
            if ("hour".equals(granularity)) {
                timeFormat = "%H:00";
                dateField = "HOUR(created_time)";
                timeRange = 24;
            } else if ("day".equals(granularity)) {
                timeFormat = "%Y-%m-%d";
                dateField = "DATE(created_time)";
                timeRange = 7;
            } else {  // week
                timeFormat = "Week %u";
                dateField = "WEEK(created_time)";
                timeRange = 4;
            }
            
            // 查询指定时间范围内的订单统计
            String sql;
            
            if ("hour".equals(granularity)) {
                sql = "SELECT HOUR(created_time) as time_slot, COUNT(*) as count " +
                     "FROM tb_order " +
                     "WHERE DATE(created_time) = CURDATE() " +
                     "GROUP BY HOUR(created_time) " +
                     "ORDER BY time_slot";
            } else if ("day".equals(granularity)) {
                sql = "SELECT DATE_FORMAT(created_time, '%Y-%m-%d') as time_slot, COUNT(*) as count " +
                     "FROM tb_order " +
                     "WHERE created_time >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) " +
                     "GROUP BY DATE(created_time) " +
                     "ORDER BY time_slot";
            } else {  // week
                sql = "SELECT CONCAT('Week ', WEEK(created_time)) as time_slot, COUNT(*) as count " +
                     "FROM tb_order " +
                     "WHERE created_time >= DATE_SUB(CURDATE(), INTERVAL 4 WEEK) " +
                     "GROUP BY WEEK(created_time) " +
                     "ORDER BY WEEK(created_time)";
            }
            
            List<Map<String, Object>> results = baseMapper.executeSql(sql);
            
            // 初始化所有时间段
            Map<String, Integer> timeSlotData = new HashMap<>();
            List<String> timeLabels = new ArrayList<>();
            
            if ("hour".equals(granularity)) {
                for (int i = 0; i < 24; i++) {
                    String timeSlot = i + ":00";
                    timeSlotData.put(timeSlot, 0);
                    timeLabels.add(timeSlot);
                }
                
                // 填充查询结果
                for (Map<String, Object> result : results) {
                    Integer hour = ((Number) result.get("time_slot")).intValue();
                    Integer count = ((Number) result.get("count")).intValue();
                    
                    String timeSlot = hour + ":00";
                    timeSlotData.put(timeSlot, count);
                }
                
                flowData.put("timeLabels", timeLabels);
                
            } else if ("day".equals(granularity)) {
                // 初始化最近7天日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_MONTH, -6);
                
                for (int i = 0; i < 7; i++) {
                    String date = sdf.format(cal.getTime());
                    timeSlotData.put(date, 0);
                    timeLabels.add(date);
                    cal.add(Calendar.DAY_OF_MONTH, 1);
                }
                
                // 填充查询结果
                for (Map<String, Object> result : results) {
                    String date = (String) result.get("time_slot");
                    Integer count = ((Number) result.get("count")).intValue();
                    
                    if (timeSlotData.containsKey(date)) {
                        timeSlotData.put(date, count);
                    }
                }
                
                flowData.put("dateLabels", timeLabels);
                
            } else {  // week
                // 初始化最近4周
                for (int i = 1; i <= 4; i++) {
                    String week = "Week " + i;
                    timeSlotData.put(week, 0);
                    timeLabels.add(week);
                }
                
                // 填充查询结果
                for (Map<String, Object> result : results) {
                    String week = (String) result.get("time_slot");
                    Integer count = ((Number) result.get("count")).intValue();
                    
                    if (timeSlotData.containsKey(week)) {
                        timeSlotData.put(week, count);
                    }
                }
                
                flowData.put("weekLabels", timeLabels);
            }
            
            // 提取订单数量数组
            List<Integer> orderCounts = timeLabels.stream()
                .map(label -> timeSlotData.get(label))
                .collect(Collectors.toList());
            
            flowData.put("orderCounts", orderCounts);
            
        } catch (Exception e) {
            // 查询失败时返回默认数据
            if ("hour".equals(granularity)) {
                String[] timeLabels = new String[24];
                int[] orderCounts = new int[24];
                
                for (int i = 0; i < 24; i++) {
                    timeLabels[i] = i + ":00";
                    orderCounts[i] = 0;
                }
                
                flowData.put("timeLabels", timeLabels);
                flowData.put("orderCounts", orderCounts);
                
            } else if ("day".equals(granularity)) {
                List<String> dateLabels = new ArrayList<>();
                List<Integer> orderCounts = new ArrayList<>();
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_MONTH, -6);
                
                for (int i = 0; i < 7; i++) {
                    dateLabels.add(sdf.format(cal.getTime()));
                    orderCounts.add(0);
                    cal.add(Calendar.DAY_OF_MONTH, 1);
                }
                
                flowData.put("dateLabels", dateLabels);
                flowData.put("orderCounts", orderCounts);
                
            } else {  // week
                String[] weekLabels = {"第一周", "第二周", "第三周", "第四周"};
                int[] orderCounts = {0, 0, 0, 0};
                
                flowData.put("weekLabels", weekLabels);
                flowData.put("orderCounts", orderCounts);
            }
        }
        
        return flowData;
    }
    
    @Override
    public Map<String, Object> getAbnormalOrders(Integer page, Integer size) {
        // 默认分页参数
        page = (page == null || page < 1) ? 1 : page;
        size = (size == null || size < 1) ? 10 : size;
        
        // 创建分页对象
        Page<Order> pageParam = new Page<>(page, size);
        
        try {
            // 异常订单的定义：
            // 1. 长时间未完成的订单（配送中状态超过2小时）
            // 2. 支付但未分配骑手的订单（待接单状态超过30分钟）
            // 3. 未支付订单（待支付状态超过30分钟）
            
            // 获取基准时间点
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.HOUR_OF_DAY, -2);
            Date twoHoursAgo = cal.getTime();
            
            cal = Calendar.getInstance();
            cal.add(Calendar.MINUTE, -30);
            Date thirtyMinutesAgo = cal.getTime();
            
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.and(wrapper -> wrapper
                    // 配送中超过2小时
                    .or(w -> w.eq(Order::getStatus, 2).lt(Order::getUpdatedTime, twoHoursAgo))
                    // 待接单超过30分钟
                    .or(w -> w.eq(Order::getStatus, 1).lt(Order::getUpdatedTime, thirtyMinutesAgo))
                    // 待支付超过30分钟
                    .or(w -> w.eq(Order::getStatus, 0).lt(Order::getCreatedTime, thirtyMinutesAgo))
                )
                .orderByAsc(Order::getCreatedTime);
            
            // 执行查询
            IPage<Order> pageResult = page(pageParam, queryWrapper);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("pages", pageResult.getPages());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            
            return result;
            
        } catch (Exception e) {
            // 查询失败返回空结果
            Map<String, Object> result = new HashMap<>();
            result.put("records", new ArrayList<>());
            result.put("total", 0);
            result.put("pages", 0);
            result.put("current", page);
            result.put("size", size);
            
            return result;
        }
    }

    @Override
    public List<Map<String, Object>> getMerchantRanking(Map<String, Object> params) {
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        
        try {
            // 构建SQL查询
            String rankingSql = "SELECT m.id, m.shop_name as name, m.address, " +
                               "COUNT(o.id) as orderCount, " +
                               "IFNULL(SUM(o.pay_amount), 0) as orderAmount " +
                               "FROM tb_order o " +
                               "JOIN tb_merchant m ON o.merchant_id = m.id " +
                               "WHERE 1=1 ";
            
            // 添加时间范围
            if (startDate != null && !startDate.isEmpty()) {
                rankingSql += "AND o.created_time >= '" + startDate + " 00:00:00' ";
            }
            
            if (endDate != null && !endDate.isEmpty()) {
                rankingSql += "AND o.created_time <= '" + endDate + " 23:59:59' ";
            }
            
            rankingSql += "GROUP BY m.id " +
                         "ORDER BY orderAmount DESC " +
                         "LIMIT 10"; // 只返回前10名
            
            // 执行查询
            List<Map<String, Object>> results = baseMapper.executeSql(rankingSql);
            
            // 计算占比
            if (!results.isEmpty()) {
                double totalAmount = results.stream()
                    .mapToDouble(m -> ((Number) m.get("orderAmount")).doubleValue())
                    .sum();
                
                // 添加占比和颜色
                String[] colors = {"#f56c6c", "#e6a23c", "#409eff", "#67c23a", "#909399", 
                                  "#336699", "#ff9900", "#cc3333", "#99cc33", "#666666"};
                
                for (int i = 0; i < results.size(); i++) {
                    Map<String, Object> item = results.get(i);
                    double amount = ((Number) item.get("orderAmount")).doubleValue();
                    int percentage = (int) Math.round((amount / totalAmount) * 100);
                    
                    item.put("percentage", percentage > 100 ? 100 : percentage);
                    item.put("color", colors[i % colors.length]);
                }
            }
            
            return results;
            
        } catch (Exception e) {
            e.printStackTrace();
            // 查询失败返回空列表
            return new ArrayList<>();
        }
    }

    @Override
    public Map<String, Object> getOrderDetailWithItems(Long orderId) {
        // 获取订单基本信息
        Order order = getById(orderId);
        if (order == null) {
            return new HashMap<>();
        }
        
        Map<String, Object> result = new HashMap<>();
        
        // 转换订单信息为Map
        result.put("id", order.getId());
        result.put("orderNo", order.getOrderNo());
        result.put("userId", order.getUserId());
        result.put("merchantId", order.getMerchantId());
        result.put("riderId", order.getRiderId());
        result.put("status", order.getStatus());
        result.put("totalAmount", order.getTotalAmount());
        result.put("deliveryFee", order.getDeliveryFee());
        result.put("payAmount", order.getPayAmount());
        result.put("payType", order.getPayType());
        result.put("address", order.getAddress());
        result.put("phone", order.getPhone());
        result.put("remarks", order.getRemarks());
        result.put("deliveryMode", order.getDeliveryMode());
        result.put("createdTime", order.getCreatedTime());
        result.put("payTime", order.getPayTime());
        result.put("updatedTime", order.getUpdatedTime());
        
        // 订单状态文本
        result.put("statusText", order.getStatusName());
        
        // 处理商品数据
        String itemsJson = order.getItems();
        result.put("items", itemsJson);
        
        // 尝试从数据库获取商家信息
        try {
            if (order.getMerchantId() != null) {
                Map<String, Object> merchantInfo = baseMapper.selectMerchantById(order.getMerchantId());
                if (merchantInfo != null) {
                    result.put("merchantName", merchantInfo.get("name"));
                    result.put("merchantAddress", merchantInfo.get("address"));
                    result.put("merchantPhone", merchantInfo.get("phone"));
                }
            }
        } catch (Exception e) {
            log.error("获取商家信息失败", e);
        }
        
        return result;
    }

    @Override
    public boolean updateOrderRider(Long orderId, Long riderId) {
        try {
            if (orderId == null || riderId == null) {
                log.error("订单ID或骑手ID为空");
                return false;
            }
            
            Order order = getById(orderId);
            if (order == null) {
                log.error("订单不存在: {}", orderId);
                return false;
            }
            
            // 更新订单的骑手ID和状态
            order.setRiderId(riderId);
            order.setStatus(2); // 假设状态2为骑手已接单
            order.setUpdatedTime(new Date());
            
            boolean result = updateById(order);
            if (result) {
                log.info("订单 {} 成功分配给骑手 {}", orderId, riderId);
            } else {
                log.error("更新订单 {} 的骑手信息失败", orderId);
            }
            
            return result;
        } catch (Exception e) {
            log.error("更新订单骑手信息异常", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean rateRider(Long orderId, Long riderId, Float rating, String comment) {
        try {
            if (orderId == null || riderId == null || rating == null) {
                log.error("评价参数不完整");
                return false;
            }
            
            // 验证评分范围
            if (rating < 1 || rating > 5) {
                log.error("评分必须在1-5之间");
                return false;
            }
            
            // 验证订单是否存在
            Order order = getById(orderId);
            if (order == null) {
                log.error("订单不存在: {}", orderId);
                return false;
            }
            
            // 验证是否为该骑手配送的订单
            if (order.getRiderId() == null || !order.getRiderId().equals(riderId)) {
                log.error("骑手{}未配送订单{}", riderId, orderId);
                return false;
            }
            
            // 验证订单是否已完成
            if (order.getStatus() != 3) { // 假设状态3为已完成
                log.error("订单{}尚未完成，无法评价", orderId);
                return false;
            }
            
            // 标记订单已评价
            order.setIsRated(1); // 假设isRated字段表示是否已评价：0-未评价，1-已评价
            order.setUpdatedTime(new Date());
            updateById(order);
            
            // 更新骑手评分
            Rider rider = riderService.getById(riderId);
            if (rider == null) {
                log.error("骑手不存在: {}", riderId);
                return false;
            }
            
            // 获取骑手当前评分和订单数
            Float currentRating = rider.getRating();
            Integer completedOrderCount = rider.getCompletedOrderCount();
            
            if (currentRating == null) {
                currentRating = 0f;
            }
            
            if (completedOrderCount == null) {
                completedOrderCount = 0;
            }
            
            // 计算新的平均评分
            Float newRating;
            if (completedOrderCount == 0) {
                newRating = rating;
            } else {
                // 使用加权平均计算新评分：(当前评分*已完成订单数 + 新评分) / (已完成订单数 + 1)
                newRating = (currentRating * completedOrderCount + rating) / (completedOrderCount + 1);
            }
            
            // 四舍五入到一位小数
            newRating = Math.round(newRating * 10) / 10f;
            
            // 更新骑手评分
            rider.setRating(newRating);
            rider.setCompletedOrderCount(completedOrderCount + 1);
            rider.setUpdatedTime(new Date());
            boolean updateResult = riderService.updateById(rider);
            
            if (updateResult) {
                log.info("成功更新骑手{}的评分为{}", riderId, newRating);
            } else {
                log.error("更新骑手{}评分失败", riderId);
                return false;
            }
            
            // 保存评价记录到评价表
            // 这里假设有一个RiderRating实体和对应的service
            try {
                // 在实际项目中需要添加评价表和服务
                /*
                RiderRating riderRating = new RiderRating();
                riderRating.setOrderId(orderId);
                riderRating.setRiderId(riderId);
                riderRating.setUserId(order.getUserId());
                riderRating.setRating(rating);
                riderRating.setComment(comment);
                riderRating.setCreatedTime(new Date());
                riderRatingService.save(riderRating);
                */
                
                // 临时使用日志记录评价信息
                log.info("用户{}对骑手{}的订单{}评分：{}，评价内容：{}", 
                    order.getUserId(), riderId, orderId, rating, comment);
            } catch (Exception e) {
                log.error("保存评价记录异常", e);
                // 评价记录保存失败不影响主流程
            }
            
            return true;
        } catch (Exception e) {
            log.error("评价骑手异常", e);
            return false;
        }
    }
} 